import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Timer? timer;
  int count = 60;
  begincount() {
    if (count == 60) {
      setState(() {
        count--;
        timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          if (count == 0) {
            setState(() {
              count = 60;
              timer.cancel();
            });
          } else {
            setState(() {
              count--;
            });
          }
        });
      });
    } else {
      PromptAction.showErrorToast('不要重复点击');
    }
  }

  Widget gettext() {
    if (count < 60) {
      return Text('剩余$count秒');
    } else {
      return const Text('获取验证码');
    }
  }

  login() async {
    // PromptAction.showToast(_phoneController.text);
    if (_phoneController.text.isEmpty) {
      return PromptAction.showErrorToast('手机号不能为空');
    }
    if (_codeController.text.isEmpty) {
      return PromptAction.showErrorToast('验证码不能为空');
    }
    RegExp phonereg = RegExp(r'^1[3-9]\d{9}$');
    if (!phonereg.hasMatch(_phoneController.text)) {
      return PromptAction.showErrorToast('手机号格式不正确');
    }
    RegExp codereg = RegExp(r'^\d{6}$');
    if (!codereg.hasMatch(_codeController.text)) {
      return PromptAction.showErrorToast('验证码格式不正确');
    }
    final res = await loginAPI(
        {'mobile': _phoneController.text, 'code': _codeController.text});
    //清除定时器
    timer?.cancel();
    //返回上一页
    Navigator.pop(context);
    tokenManager.setToken(res['token'], refreshToken: res['refreshToken']);
    // 一旦登录成功之后, 通知我的页面, 重新获取用户信息, 进行渲染
    eventBus.fire(LoginEvent());
  }

  sendcode() async {
    if (count == 60) {
      if (_phoneController.text.isEmpty) {
        return PromptAction.showErrorToast('手机号不能为空');
      }
      RegExp reg = RegExp(r'^1[3-9]\d{9}$');
      if (!reg.hasMatch(_phoneController.text)) {
        return PromptAction.showErrorToast('手机号格式不正确');
      }
      final res = await sendCodeAPI({'mobile': _phoneController.text});
      PromptAction.showsuccessToast('发送成功');
      Future.delayed((const Duration(seconds: 3)), () {
        _codeController.text = res['code'];
      });
      begincount();
    }
  }

  final TextEditingController _phoneController = TextEditingController(); // 手机号
  final TextEditingController _codeController = TextEditingController(); // 验证码
  @override
  void initState() {
    super.initState();
    _phoneController.text = '18888888888';
  }

  @override
  void dispose() {
    timer?.cancel(); // 当页面销毁时，清除定时器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    //
                    sendcode();
                  },
                  child: gettext(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
